package com.edu.service.impl;

import com.edu.dao.CheckGroupDao;
import com.edu.entity.PageResult;
import com.edu.entity.QueryPageBean;
import com.edu.pojo.CheckGroup;
import com.edu.service.CheckGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        Integer id = checkGroup.getId();

        if(checkitemIds != null && checkitemIds.length > 0){
            for (Integer checkitemId : checkitemIds) {
                HashMap<String, Integer> map = new HashMap();
                map.put("checkgroupId",id);
                map.put("checkitemId",checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    public List<Integer> findCheckitemIdsByCheckgroupId(Integer id) {
        return checkGroupDao.findCheckitemIdsByCheckgroupId(id);
    }

    public void edit(CheckGroup checkGroup, Integer[] checkItemIds) {
        checkGroupDao.edit(checkGroup);

        checkGroupDao.deleteAssocication(checkGroup.getId());

        Integer id = checkGroup.getId();
        if(checkItemIds != null && checkItemIds.length > 0){
            for (Integer checkItemId : checkItemIds) {
                HashMap<String,Integer> map = new HashMap();
                map.put("checkgroupId",id);
                map.put("checkitemId",checkItemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    public void deleteById(Integer id) {
        long countByCheckGroupId = checkGroupDao.findCountByCheckGroupId(id);
        if(countByCheckGroupId>0){
            new RuntimeException();
        }
        checkGroupDao.deleteById(id);
    }

    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
